package com.ruoyi.xyq.config;

import com.ruoyi.xyq.domain.Withdrawal;
import com.ruoyi.xyq.domain.WithdrawalRequest;
import com.ruoyi.xyq.mapper.WithdrawalMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WithdrawalAuditConsumer {

    @Autowired
    private WithdrawalMapper withdrawalMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "withdrawal.delay.queue")
    public void handleWithdrawalRequest(WithdrawalRequest request) {
        System.out.println("收到请求" + request);
        try {
            boolean isApproved = Math.random() < 0.8; // 80% 概率审核通过

            if (isApproved) {
                // 审核成功：仅更新状态为"成功"（预扣已在发送前完成）
                Withdrawal withdrawal = request.getWithdrawal();
                withdrawal.setStatus(0L);
                withdrawal.setCashWithdrawal(withdrawal.getCashWithdrawal() + request.getMoney());
                withdrawalMapper.updateWithdrawal(withdrawal);
                System.out.println("审核成功" + withdrawal);
            } else {
                // 审核失败：回滚预扣金额（关键修改点）
                rabbitTemplate.convertAndSend(
                        "withdrawal.dead.letter.exchange",
                        "withdrawal.dead.letter.routing.key",
                        request
                );
                 System.out.println("审核失败" + request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}